/**
 * 模板管理工具模块
 * 负责模板选择弹窗及其相关业务逻辑的封装
 */

import axios from 'axios'
import config from '@/config'

export class TemplateManager {
  constructor(vueInstance) {
    this.vm = vueInstance
  }

  // 显示模板选择器并加载模板数据
  async showTemplateSelector(satellite) {
    this.vm.selectedSatellite = satellite
    this.vm.templateSelectorVisible = true

    try {
      const response = await axios.get(`${config.API_BASE_URL}/api/templates/`)
      if (response.data && response.data.success && Array.isArray(response.data.data)) {
        // 兼容字段：后端可能返回 task_blocks_layout
        this.vm.templates = response.data.data.map(t => ({
          ...t,
          taskBlocks: t.task_blocks_layout || []
        }))
      } else {
        this.vm.templates = Array.isArray(response.data) ? response.data : []
      }
    } catch (error) {
      console.error('加载模板失败:', error)
      this.vm.templates = []
    }
  }

  // 关闭模板选择器
  closeTemplateSelector() {
    this.vm.templateSelectorVisible = false
    this.vm.selectedSatellite = null
    this.vm.selectedTemplate = null
  }

  // 选择模板
  selectTemplate(template, type) {
    this.vm.selectedTemplate = {
      ...template,
      type
    }
  }

  // 应用选中的模板到当前选中卫星
  applySelectedTemplate() {
    const vm = this.vm
    if (!vm.selectedTemplate || !vm.selectedSatellite) {
      return
    }

    // 保存历史记录（用于撤销）
    if (vm.saveToHistory) {
      vm.saveToHistory()
    }

    if (vm.selectedTemplate.type === 'project') {
      const templateTasks = (vm.selectedTemplate.taskBlocks && vm.selectedTemplate.taskBlocks.length > 0)
        ? vm.selectedTemplate.taskBlocks
        : (vm.selectedTemplate.task_blocks_layout || [])

      if (templateTasks && templateTasks.length > 0) {
        // 防止 watcher 重复保存
        vm.isUpdatingScheduleItems = true

        // 清除当前卫星下的任务块
        vm.scheduleItems = vm.scheduleItems.filter(item => item.satelliteId !== vm.selectedSatellite.id)

        // 智能获取下一个可用开始天
        const findNextAvailableStartDay = () => {
          const satelliteItems = vm.scheduleItems.filter(item => item.satelliteId === vm.selectedSatellite.id)
          if (satelliteItems.length === 0) return 0
          const maxEndDay = Math.max(...satelliteItems.map(item => item.startDay + item.duration))
          return maxEndDay
        }

        templateTasks.forEach((taskBlock, index) => {
          const duration = parseInt(taskBlock.duration) || 1

          // 从模板中提取设备配置
          const extractedDevices = vm.extractRequiredDevicesFromTemplate ? vm.extractRequiredDevicesFromTemplate(taskBlock) : []

          // 构造每日设备配置（优先模板里的 dayConfigs）
          let appliedDayConfigs = []
          if (taskBlock.dayConfigs && Array.isArray(taskBlock.dayConfigs) && taskBlock.dayConfigs.length > 0) {
            appliedDayConfigs = [...taskBlock.dayConfigs]
            while (appliedDayConfigs.length < duration) appliedDayConfigs.push([])
          } else if (extractedDevices.length > 0) {
            for (let i = 0; i < duration; i++) appliedDayConfigs.push([...extractedDevices])
          } else {
            for (let i = 0; i < duration; i++) appliedDayConfigs.push([])
          }

          const scheduleItem = {
            id: Date.now() + Math.random() + index,
            satelliteId: vm.selectedSatellite.id,
            title: taskBlock.name || '未命名任务',
            type: taskBlock.type || 'task',
            startDay: findNextAvailableStartDay(),
            duration,
            color: taskBlock.color || '#3498db',
            requiredDevice: taskBlock.requiredDevice || '',
            requiredDevices: vm.extractRequiredDevicesFromTemplate ? vm.extractRequiredDevicesFromTemplate(taskBlock) : [],
            dayConfigs: appliedDayConfigs,
            description: taskBlock.description || `从项目模板 "${vm.selectedTemplate.name}" 导入: ${taskBlock.name}`,
            deviceCapacities: vm.createDeviceCapacitiesFromTemplate ? vm.createDeviceCapacitiesFromTemplate(taskBlock) : {}
          }

          vm.scheduleItems.push(scheduleItem)
        })

        vm.hasScheduleData = true
        vm.isUpdatingScheduleItems = false

        // 冲突检测
        if (vm.detectDeviceConflicts) {
          const conflicts = vm.detectDeviceConflicts()
          if (conflicts.length > 0 && vm.markConflictingTasks) vm.markConflictingTasks(conflicts)
          else if (vm.clearConflictMarks) vm.clearConflictMarks()
        }

        // 强制刷新与天数校验
        vm.$forceUpdate && vm.$forceUpdate()
        vm.ensureSufficientDays && vm.ensureSufficientDays()

        // 关闭弹窗
        this.closeTemplateSelector()
      } else {
        // 无任务块也立即关闭弹窗
        this.closeTemplateSelector()
      }
    } else {
      // 暂不处理其他类型，直接关闭
      this.closeTemplateSelector()
    }
  }

  // 复制其他星弹窗逻辑
  showCopySatelliteSelector() {
    const vm = this.vm
    if (!vm.selectedSatellite) {
      alert('请先选择目标卫星')
      return
    }
    vm.copySatelliteDialogVisible = true
    vm.sourceSatelliteId = null
  }

  closeCopySatelliteDialog() {
    const vm = this.vm
    vm.copySatelliteDialogVisible = false
    vm.sourceSatelliteId = null
  }

  selectSourceSatellite(satelliteId) {
    this.vm.sourceSatelliteId = satelliteId
  }

  confirmCopySatellite() {
    const vm = this.vm
    if (!vm.sourceSatelliteId || !vm.selectedSatellite) {
      alert('请选择源卫星')
      return
    }

    const sourceItems = vm.scheduleItems.filter(item => item.satelliteId === vm.sourceSatelliteId)
    if (sourceItems.length === 0) {
      alert('源卫星没有任务块可复制')
      return
    }

    vm.isUpdatingScheduleItems = true

    // 替换目标卫星的现有任务块
    vm.scheduleItems = vm.scheduleItems.filter(item => item.satelliteId !== vm.selectedSatellite.id)

    const copiedItems = sourceItems.map((item, index) => ({
      ...item,
      id: Date.now() + Math.random() + index,
      satelliteId: vm.selectedSatellite.id
    }))

    vm.scheduleItems.push(...copiedItems)
    vm.isUpdatingScheduleItems = false

    // 修复重叠
    if (vm.validateAndFixOverlaps) {
      vm.validateAndFixOverlaps(vm.selectedSatellite.id)
    }

    // 冲突检测
    if (vm.detectDeviceConflicts) {
      const conflicts = vm.detectDeviceConflicts()
      if (conflicts.length > 0 && vm.markConflictingTasks) vm.markConflictingTasks(conflicts)
      else if (vm.clearConflictMarks) vm.clearConflictMarks()
    }

    // 关闭弹窗
    this.closeCopySatelliteDialog()
    this.closeTemplateSelector()
  }
}